package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 部门管理 服务实现
 * 
 * @author ruoyi
 */
@Service
public class SysDeptServiceImpl implements ISysDeptService
{
    @Resource
    private SysDeptMapper deptMapper;

    @Resource
    private SysRoleMapper roleMapper;
    
    @Autowired
    private SysUserMapper userMapper;

    /**
     * 查询部门管理数据
     * 
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept)
    {
        return deptMapper.selectDeptList(dept);
    }


    @Override
    public List<SysDept> selectAllDeptList()
    {
        return deptMapper.selectAllDeptList();
    }

    /**
     * 构建前端所需要树结构
     * 
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts)
    {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<String> tempList = new ArrayList<String>();
        for (SysDept dept : depts)
        {
            tempList.add(dept.getDeptId().toString());
        }
        for (Iterator<SysDept> iterator = depts.iterator(); iterator.hasNext();)
        {
            SysDept dept = (SysDept) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId().toString()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     * 
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts)
    {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     * 
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Integer> selectDeptListByRoleId(Long roleId)
    {
        SysRole role = roleMapper.selectRoleById(roleId);
        return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }

    /**
     * 根据部门ID查询信息
     * 
     * @param deptIdCode 全局部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptByIdCode(String deptIdCode)
    {
        return deptMapper.selectDeptByIdCode(deptIdCode);
    }

    @Override
    public SysDept selectDeptById(String deptId)
    {
        return deptMapper.selectDeptByIdCode(deptId);
    }
    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(SysDept sysDept)
    {
        String progenitorStr = getProgenitorStr(sysDept);
        return deptMapper.selectNormalChildrenDeptById(sysDept.getDeptId().toString(),progenitorStr);
    }

    /**
     * 是否存在子节点
     * 
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(String deptId)
    {
        int result = deptMapper.hasChildByDeptId(deptId);
        return result > 0 ? true : false;
    }

    /**
     * 查询部门是否存在用户
     * 
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(String deptId)
    {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0 ? true : false;
    }

    /**
     * 校验部门名称是否唯一
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(SysDept dept)
    {
        String deptId = StringUtils.isNull(dept.getDeptId()) ? null : dept.getDeptId().toString();
        SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId().toString());
        if (StringUtils.isNotNull(info) && !info.getDeptId().equals(deptId))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存部门信息
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insertDept(SysDept dept)
    {
        SysDept info = deptMapper.selectDeptById(dept.getParentId().toString());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new CustomException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return deptMapper.insertDept(dept);
    }

    @Override
    public int insertDeptByOne(SysDept dept)
    {
        return deptMapper.insertDept(dept);
    }

    /**
     * 修改保存部门信息
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int updateDept(SysDept dept)
    {
       int result=0;
        if(dept.getParentId()!=null){
            SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId().toString());
            SysDept oldDept = deptMapper.selectDeptById(dept.getDeptId().toString());
            if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
            {
                String progenitorStr = getProgenitorStr(newParentDept);
                String oldAncestors = getProgenitorStr(oldDept);
                String newAncestors = progenitorStr + "," + newParentDept.getDeptId();
                dept.setAncestors(newAncestors);
                updateDeptChildren(dept, newAncestors, oldAncestors);
            }
             result = deptMapper.updateDept(dept);
            if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()))
            {
                // 如果该部门是启用状态，则启用该部门的所有上级部门
                updateParentDeptStatus(dept);
            }

        }else {
             result = deptMapper.updateDept(dept);
            if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()))
            {
                // 如果该部门是启用状态，则启用该部门的所有上级部门
                updateParentDeptStatus(dept);
            }
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     * 
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(SysDept dept)
    {
        String updateBy = dept.getUpdateBy();
        dept = deptMapper.selectDeptById(dept.getDeptId().toString());
        dept.setUpdateBy(updateBy);
        String progenitorStr = getProgenitorStr(dept);
        dept.setAncestors(progenitorStr);
        deptMapper.updateDeptStatus(dept);
    }

    /**
     * 修改子元素关系
     * 
     * @param sysDept 被修改的部门
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(SysDept sysDept, String newAncestors, String oldAncestors)
    {
        String ancestors = getProgenitorStr(sysDept);
        List<SysDept> children = deptMapper.selectChildrenDeptById(sysDept.getDeptId().toString(),ancestors);

        for (SysDept child : children)
        {
            String progenitorStr = getProgenitorStr(child);
            child.setAncestors(progenitorStr.replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
//            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     * 
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(String deptId)
    {
        return deptMapper.deleteDeptById(deptId);
    }


    @Override
    public int deleteDeptByIdCode(String deptIdCode)
    {
        return deptMapper.deleteDeptByIdCode(deptIdCode);
    }

    @Override
    public String getProgenitor(SysDept t)
    {
        return getProgenitorStr(t);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t)
    {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t)
    {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext())
        {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().equals(t.getDeptId()))
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    /**
     * 递归获取祖节点
     * @param list
     * @param t
     * @param result
     */
    private void recursionProgenitor(List<SysDept> list, SysDept t, List<SysDept> result) {
        if (hasParent(t)) {
            // 得到父节点列表
            for (SysDept dept : list) {
                if (!result.contains(dept) & dept.getDeptId().equals(t.getParentId())) {
                    t = dept;
                    result.add(dept);
                    recursionProgenitor(list, dept, result);
                }
            }
        }
    }

    /**
     * 判断是否有父节点
     */
    private boolean hasParent(SysDept t)
    {
        return StringUtils.isNotNull(t.getDeptId());
    }

    /**
     * 获取祖节点字符串
     * @param t
     * @return
     */
    private String getProgenitorStr(SysDept t) {
        List<SysDept> sysDepts = deptMapper.selectAllDeptList();
        ArrayList<SysDept> syncSysProgenitors = new ArrayList<>();
        recursionProgenitor(sysDepts, t, syncSysProgenitors);
        return appendProgenitorAll(syncSysProgenitors);
    }
    /**
     * 递归获取祖节点
     * @param result
     */
    private String appendProgenitorAll(List<SysDept> result) {
        if (result.size()>0){
            StringBuffer stringBuffer = new StringBuffer();
            StringBuffer append = stringBuffer.append(result.get(0).getParentId());
            for (int i = 1; i < result.size(); i++) {
                if (result.get(i).getParentId()!=null){
                    append = append.append(",").append(result.get(i).getParentId());
                }
            }
            return append.toString();
        }
        return null;
    }
	
    /**
     * 获取当前节点下所有子节点通过部门Id
     * @param deptId
     * @return
     */
    @Override
    public List<SysDept> getChildListByDeptId(String deptId){
        List<SysDept> result =  new ArrayList<>();
        result.add(deptMapper.selectDeptById(deptId));
        getChildListByParentId(deptId ,result);
        return result;
    }

    /**
     * 递归列表
     */
    private void getChildListByParentId(String deptId, List<SysDept> result)
    {
        List<SysDept> list = deptMapper.selectDeptByParentId(deptId);
        if(!CollectionUtils.isEmpty(list)){
            result.addAll(list);
        }
        for (SysDept sysDept : list) {
            getChildListByParentId(sysDept.getDeptId().toString(), result);
        }
    }
	
	@Override
	public List<Map<String, Object>> findOrgUserTree(Long pid) {
	    // 查找根节点
	    List<Map<String, Object>> list = deptMapper.findListByPid(pid);
	    List<Map<String, Object>> children;
	    for (Map<String, Object>  m: list) {
	        children = findOrgUserTree(Long.parseLong(m.get("id").toString()));
	        if (children != null && children.size() != 0) { //查询组织机构的子节点，并赋值给元素“children”
	            m.put("children",children);
	        } else {
	            children = userMapper.findUserByOrgId(Long.parseLong(m.get("id").toString())); //当根节点组织结构时，查询结构下面的员工，并赋值给根节点组织机构的children
	            if (children != null && children.size() != 0) {
	                m.put("children",children);
	            }
	            //设置叶子组织机构（没有人员），为不可选 isDisabled为vuetree节点的属性，不能勾选
	            if(children == null ||children.size() == 0){
	                m.put("isDisabled",true);
	            }
	        }
	    }
	    return list;}
}
